package com.qf.votedemo.webSocket;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 刘欣
 * @createTime 2023/2/25 14:39
 * @description
 */
@Component
@ServerEndpoint("/webSocket/{id}")
@Slf4j
public class WebSocketServer {

    //保存页面 websocket连接对象的 map对象
    private static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    private Session session = null;

    /**
     * 打开webSocket连接
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        log.debug("-------有新的客户连接------");
        this.session = session;
        sessionMap.put(id, session);
    }

    /**
     * 响应客户端信息
     */
    @OnMessage
    public void onMsg(String msg) throws IOException {
        session.getBasicRemote().sendText(msg);
    }

    /**
     * 提供外部使用
     */
    public static void sengMsg(String msg) throws IOException {
        if (sessionMap != null && sessionMap.size() > 0) {
            Session session = sessionMap.get("1");
            session.getBasicRemote().sendText(msg);
        }
    }

    @OnClose
    public void close() {
        sessionMap.remove(1);
    }

    //处理webSocket异常
    @OnError
    public void error(Throwable throwable) {

        log.debug("客户端连接出现问题");

    }

}
